﻿using Assets.Scripts.config;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YeqianFramework;
using YeqianFramework.common;
using YeqianFramework.core;
using UnityEngine;
using System.Threading;

namespace Assets.Scripts.Manager
{
	public class TheThreeBodyGameManager : MonoBehaviourSingleton<TheThreeBodyGameManager>
	{
		/// <summary>
		/// 游戏的全局配置
		/// </summary>
		public GlobalGameConfig GameConfig;
		public string configPath;

		/// <summary>
		/// 行星数据
		/// </summary>
		public PlanetData PlanetData;
		/// <summary>
		/// 恒星数据
		/// </summary>
		public Dictionary<string, FixedStarData> FixedStarsDic { get; private set; }

		/// <summary>
		/// 是否以及加载完
		/// </summary>
		public bool isConfigLoadDown { get; private set; }
		/// <summary>
		/// 全局游戏配置加载完全的事件
		/// </summary>
		public event Action onGlobalConfigLoadComplete = ()=> { };

		private SynchronizationContext context;
		public void LoadGameConfig()
		{
			configPath = YQFKContext.Current.YQFKConfig.GameConfigDirectory + "GlobalGameConfig.xml";
			isConfigLoadDown = false;
			//StartCoroutine(LoadConfig());
			context = SynchronizationContext.Current;
			if(context == null)
			{
				Debug.LogError("SynchronizationContext.Current == null");
			}
			new Thread(new ThreadStart(LoadConfig)).Start();

			FixedStarsDic = new Dictionary<string, FixedStarData>();
		}

		private void LoadConfig()
		{
			GlobalGameConfig config = XmlHelper.Xml2Object<GlobalGameConfig>(configPath);

			//LoadConfigCallback();
			context.Post(new SendOrPostCallback(LoadConfigCallback), config);
		}

		private void LoadConfigCallback(object state)
		{
			GameConfig = state as GlobalGameConfig;
			PlanetData = GameConfig.Planet;
			foreach (var item in GameConfig.FixedStars)
			{
				FixedStarsDic.Add(item.Name, item);
			}

			Debug.Log("全局游戏配置加载完成！");
			isConfigLoadDown = true;
			onGlobalConfigLoadComplete();
		}

		protected override void Init() { }
	}
}
